package com.team7.happycommunity.gatway.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.team7.happycommunity.gatway.common.CommonResult;
import com.team7.happycommunity.gatway.exception.GatawayException;
import com.team7.happycommunity.gatway.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import sun.misc.Request;

import java.util.ArrayList;
import java.util.List;


@Component
public class PropertySecurityFilter extends ZuulFilter {

    @Autowired
    JWTUtils jwtUtils;

    /**
     * 运行阶段
     * pre、route、post、error
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 开关控制
     * @return
     */
    @Override
    public boolean shouldFilter() {
        List<String> list_url = new ArrayList<String>();
        list_url.add("/propertymanagement/user/test2");
        list_url.add("/propertymanagement/area/getone");
//        list_url.add("/propertymanagement/propertyservice");
        // 测试 路径
        for(String url: list_url){
            if (RequestContext.getCurrentContext().getRequest().getRequestURI().contains(url)){
                return true;
            }
        }
        return false;
    }



    @Override
    public Object run(){

        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取 用户名信息
        String username = requestContext.getRequest().getHeader("username");
        String token = requestContext.getRequest().getHeader("token");
        System.out.println(token);
        System.out.println(username);
        // 解密 token 信息
        String result_name = jwtUtils.unsign(token,String.class);
        if(result_name == null || !result_name.equals(username)){
            // 认证失败拒绝访问
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(200);
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(CommonResult.failed("abs"));
            requestContext.setResponseBody(jsonObject.toJSONString());
        }
        return null;
    }
}
